const CateController = {};
const queryPromise = require("../model/query-promise.js")
const { dateFormat, getNowDate } = require('../util/tool.js')


CateController.list = (req, res) => {
    // 取出session中的用户信息
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    res.render("cate-list.html", { userInfo })
}

// CateController.cate = (req, res) => {
//     // 1.获取所有分类
//     let sql = "select * from category";
//     queryPromise(sql).then(result => {
//         // 2.返回json数据响应给调用者
//         res.json(result)
//     })
// }

CateController.cate = async (req, res) => {
    // 1.获取所有分类
    let sql = "select * from category order by cate_id desc";
    let result = await queryPromise(sql)
    // 2.返回json数据响应给调用者
    result.forEach(item => {
        item['add_date'] = dateFormat(item['add_date'])
        item['update_date'] = dateFormat(item['update_date'], 'YYYY-MM-DD')
    })
    res.json(result)
}


CateController.addCate = function (req, res) {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    res.render('addCate.html', { userInfo })
}

// 删除分类
CateController.delete = async (req, res) => {
    let { cat_id } = req.body;
    console.log(cat_id);
    let sql = `delete from category where cate_id = ${cat_id}`

    try {
        let result = await queryPromise(sql)
        res.json({
            code: 20000,
            message: "success"
        })
    } catch (err) {
        // 错误上报
        res.json({
            code: -1,
            message: "fail"
        })
    }

}

CateController.edit = async (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    res.render('editCate.html', { userInfo })
}

CateController.detail = async (req, res) => {
    const { cat_id } = req.query;
    let sql = `select * from category where cate_id = ${cat_id}`;
    try {
        let data = await queryPromise(sql)// [{}]
        res.json(data[0] || {})
    } catch (err) {
        res.json({})
    }
}

//数据库更新操作
CateController.updateCate = async (req, res) => {
    const { cat_id, cate_name, is_show, content } = req.body;
    // 1.判断分类名是否占用(排除自己)
    let sql = `select cate_id from category where cate_name = '${cate_name}' and cate_id != ${cat_id}`;
    let result = await queryPromise(sql)
    if (result.length) {
        // 说明占用
        res.json({
            message: "分类名已经占用",
            code: -1
        })
        return;
    }
    // 2.没占用则更新
    //更新时申明一个变量存储当前时间
    let update_date = getNowDate();
    let sql2 = `update category  set cate_name = '${cate_name}',is_show = '${is_show}' , content = '${content}',update_date = '${update_date}'
    where cate_id = ${cat_id}`;
    let result2 = await queryPromise(sql2)
    if (result2.affectedRows) {
        res.json({
            message: "更新成功",
            code: 20000
        })
    } else {
        res.json({code:-1,message:'繁忙'})
    }
}


CateController.insertCate = function (req, res) {
    let { is_show, cate_name, content } = req.body;
    //1. 判断分类名称是否占用
    let sql = `select * from category where cate_name = '${cate_name}' `
    queryPromise(sql).then(result => {
        if (result.length) {
            // 说明被占用
            res.json({
                message: "分类名占用",
                code: -1
            })
        } else {
            //2. 可用时，进行入库操作
            let add_date = getNowDate();
            let sql = `insert into category(cate_name,is_show,add_date,content) 
                    values('${cate_name}','${is_show}','${add_date}','${content}')`
            queryPromise(sql).then(result => {
                console.log(result) 
                if (result.affectedRows) {
                    res.json({
                        message: "添加分类成功",
                        code: 20000
                    })
                }
            })
        }
    })

}


module.exports = CateController;